package com.bm.main;


import java.io.IOException;
import java.net.Socket;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.bm.util.PropertiesHandler;

/**
 *
 * @author Mirza at Bimasakti
 */
public class SocketChecker {
   private final PropertiesHandler properties;

    public static String ip = "";
    public boolean connectionClosed;

    public SocketChecker() throws IOException {
        connectionClosed = false;
        properties=new PropertiesHandler();
        ip = properties.getIP();
    }
    
    private int getPort(){
        String [] listport = properties.getPorts().split(",");
        Random r = new Random();        
        return Integer.valueOf(listport[r.nextInt(listport.length)]);
    }
    
    public SocketClient getSocketClient() {
        boolean getSocketClient = false;
        int currPort = getPort();
        while (!getSocketClient) {
            Socket requestSocket = null;
            try {                
                System.out.println("Request to "+ip+" : "+currPort);
                requestSocket = new Socket(ip, currPort);
                if (connectionClosed) {
                    Object[] clientID = {Main.MacAdress};
                    SocketClient sc2 = new SocketClient(requestSocket);
                    sc2.execute("MISMS.initServer", clientID);
                    requestSocket = new Socket(ip, currPort);
                    connectionClosed = false;                    
                }                            
                SocketClient sc2 = new SocketClient(requestSocket);
                getSocketClient = true;
                return sc2;
            } catch (IOException ex) {
                System.out.print("Failed connect to : "+currPort);
                currPort = getPort();
                connectionClosed = true;
                getSocketClient = false;
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException ex1) {
                    Logger.getLogger(SocketChecker.class.getName()).log(Level.SEVERE, null, ex1);
                }
            }
        }
        return null;
    }
}